package com.ysq.track.view.panel;

import com.ysq.track.util.CommonUtil;
import com.ysq.track.util.TripleDESCBC;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;

public class MainFrame{
    Logger logger = CommonUtil.getLogger(MainFrame.class);
    
    final int mainHeight = 500;
    
    /** 主窗口 **/
    JFrame mainFrame;

    /** iv **/
    JPasswordField ivInput;
    /** key **/
    JPasswordField keyInput;
    /** content **/
    JTextArea contentArea;
    /** result **/
    JTextArea reusltArea;

    private TripleDESCBC desUtil;

    public MainFrame() throws Exception{

        initFont();
        
        desUtil = new TripleDESCBC();
        
    }

    /**
     * 设置默认字体
     */
    public void initFont(){
        Font font = new Font("宋体", Font.PLAIN, 16);

        FontUIResource fontRes = new FontUIResource(font);

        for (Enumeration<Object> keys = UIManager.getDefaults().keys();
             keys.hasMoreElements(); ) {
            
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            
            if (value instanceof FontUIResource) {
                UIManager.put(key, fontRes);
            }
        }
    }
    
    
    /**
     * 设置组件大小
     * @param comp
     * @param width
     * @param height
     */
    public void setSize(Component comp, int width, int height){
        comp.setPreferredSize(new Dimension(width, height));
    }

    /**
     * 初始化左边面板
     * @return
     */
    public JPanel createLeftPanel(){
        JPanel leftPanel = new JPanel();
        setSize(leftPanel, 350, mainHeight);
        leftPanel.setBorder(BorderFactory.createLineBorder(Color.gray));

        JLabel ivLab = new JLabel("IV : ", JLabel.LEFT);
        setSize(ivLab, 50, 25);
        ivInput = new JPasswordField();
        setSize(ivInput, 280, 25);

        JLabel keyLab = new JLabel("KEY : ", JLabel.LEFT);
        setSize(keyLab, 50, 25);
        keyInput = new JPasswordField();
        setSize(keyInput, 280, 25);

        JLabel contentLab = new JLabel("文本内容 : ", JLabel.LEFT);
        setSize(contentLab, 300, 25);

        contentArea = new JTextArea();
        
        JScrollPane areaPanel = new JScrollPane(contentArea);
        setSize(areaPanel, 340, 400);

        FlowLayout leftLayout = new FlowLayout(FlowLayout.LEFT);

        leftPanel.setLayout(leftLayout);

        leftPanel.add(ivLab);
        leftPanel.add(ivInput);

        leftPanel.add(keyLab);
        leftPanel.add(keyInput);

        leftPanel.add(contentLab);

        leftPanel.add(areaPanel);
        
        return leftPanel;
    }

    /**
     * 添加加密事件监听
     * @param btn
     */
    public void addEncListener(JButton btn){
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                /** iv **/
                String ivValue = new String(ivInput.getPassword());
                
                /** key **/
                String keyValue = new String(keyInput.getPassword());
                
                /** content **/
                String contentValue = contentArea.getText();
                
                if(CommonUtil.isBlank(keyValue)){
                    JOptionPane.showMessageDialog(mainFrame, "[KEY] 不能为空！", "警告", JOptionPane.WARNING_MESSAGE);
                }else if(CommonUtil.isBlank(contentValue)){
                    JOptionPane.showMessageDialog(mainFrame, "[文本内容] 不能为空！", "警告", JOptionPane.WARNING_MESSAGE);
                }else{
                    try {
                        String result = desUtil.encrypt2String(keyValue, ivValue, contentValue);
                        
                        /** result **/
                        reusltArea.setText(result);
                    } catch (Exception e1) {
                        JOptionPane.showMessageDialog(mainFrame, "加密错误！", "错误", JOptionPane.ERROR);
                    }
                }
            }
        });
        
    }

    /**
     * 添加解密事件
     * @param btn
     */
    public void addDecListener(JButton btn){
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                /** iv **/
                String ivValue = new String(ivInput.getPassword());

                /** key **/
                String keyValue = new String(keyInput.getPassword());

                /** content **/
                String contentValue = contentArea.getText();

                if(CommonUtil.isBlank(keyValue)){
                    JOptionPane.showMessageDialog(mainFrame, "[KEY] 不能为空！", "警告", JOptionPane.WARNING_MESSAGE);
                }else if(CommonUtil.isBlank(contentValue)){
                    JOptionPane.showMessageDialog(mainFrame, "[文本内容] 不能为空！", "警告", JOptionPane.WARNING_MESSAGE);
                }else{
                    try {
                        String result = desUtil.decrypt2String(keyValue, ivValue, contentValue);

                        /** result **/
                        reusltArea.setText(result);
                    } catch (Exception e1) {
                        JOptionPane.showMessageDialog(mainFrame, "秘钥与密文不匹配，解密失败！", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
    }

    /**
     * 设置中文字体
     * @param comp
     */
    public void setFont(Component comp){
        Font font = new Font("宋体", Font.PLAIN, 16);
        JLabel test=new JLabel("测试");
        //test.setFont();
    }
    
    
    /**
     * 创建中间面板
     * @return
     */
    public JPanel createMiddlePanel(){
        JPanel midPanel = new JPanel();
        setSize(midPanel, 100, mainHeight);
        midPanel.setBorder(BorderFactory.createLineBorder(Color.gray));

        midPanel.setLayout(new GridLayout(4, 1));
        
        JPanel pan_1 = new JPanel();
        JPanel pan_2 = new JPanel();
        JPanel pan_3 = new JPanel();
        JPanel pan_4 = new JPanel();

        midPanel.add(pan_1);
        midPanel.add(pan_2);
        midPanel.add(pan_3);
        midPanel.add(pan_4);

        JButton encBtn = new JButton("加密>>");
        addEncListener(encBtn);
        
        JButton decBtn = new JButton("解密>>");
        addDecListener(decBtn);

        pan_2.add(encBtn);

        pan_3.add(decBtn);
        
        return midPanel;
    }


    /**
     * 创建右侧面板
     * @return
     */
    public JPanel createRightPanel(){
        JPanel rightPanel = new JPanel();
        setSize(rightPanel, 350, mainHeight);
        rightPanel.setBorder(BorderFactory.createLineBorder(Color.gray));

        JLabel resultLab = new JLabel("结果内容 : ", JLabel.LEFT);
        setSize(resultLab, 300, 25);

        reusltArea = new JTextArea();
        JScrollPane resultPanel = new JScrollPane(reusltArea);
        setSize(resultPanel, 340, 440);

        Font authFont = new Font("", Font.PLAIN, 12);
        
        JLabel authLab = new JLabel("--- Created By Kingdom", JLabel.RIGHT);
        authLab.setFont(authFont);
        authLab.setForeground(Color.red);
        setSize(authLab, 340, 15);

        FlowLayout rightLayout = new FlowLayout(FlowLayout.LEFT);

        rightPanel.setLayout(rightLayout);
        
        rightPanel.add(resultLab);
        rightPanel.add(resultPanel);
        rightPanel.add(authLab);
        
        return rightPanel;
    }
    
    
    public void initFrame(){
        //JFrame.setDefaultLookAndFeelDecorated(true);

        mainFrame = new JFrame("加密/解密工具");
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        mainFrame.setResizable(false);
        
        mainFrame.setLayout(new FlowLayout(FlowLayout.LEFT));

        try {
            URL url = this.getClass().getClassLoader().getResource("middle.png");
            Image image = ImageIO.read(url);

            mainFrame.setIconImage(image);
        } catch (IOException e) {
            logger.info("icon missing");
        }

        JPanel leftPanel = createLeftPanel();

        JPanel rightPanel = createRightPanel();
        
        JPanel midPanel = createMiddlePanel();
        
        mainFrame.add(leftPanel);
        mainFrame.add(midPanel);
        mainFrame.add(rightPanel);
        
    }
    
    /**
     * 显示窗口
     */
    public void showFrame(){
        mainFrame.pack();
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(true);
        
    }
    
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    

                    MainFrame mf = new MainFrame();

                    mf.initFrame();
                    mf.showFrame();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
